//导入数据库模块
const db = require("../sql/index");
//加密插件
const bcrypt = require("bcryptjs");
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
// 导入配置文件
const config = require('../config')
// 后端开发经常会有使用http请求
const request = require('request')
// 文章的处理函数模块
const path = require('path');
// 又拍云
const upyuns = require('upyun');
const fs = require('fs');
const FormData = require('form-data');
// const bucket = new upyuns.Bucket('sportqwe', '030306', 'MB3pbgMD5xoTYfV7hQFNMalvoNxNgdYb')
const bucket = new upyuns.Bucket('ydsports', 'sport', '3aTW7QCtkkA9z1Jcppqk0qASoRw8sQDZ')

const upyun = new upyuns.Client(bucket);
// const domain = 'http://sportqwe.test.upcdn.net/'
const domain = 'http://ydsports.test.upcdn.net/'

//增加活动
exports.addactivity = (req, res) => {
    if (!req.file || req.file.fieldname !== 'img') return res.cc('图片是必选参数！')
    const sql = `select * from activity where city_id= ${req.body.city_id}`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        if (results.length == 1 && results[0].city_id == req.body.city_id) return res.cc('城市已经存在，请更换后重试！')
        if (results.length == 0) {
            fs.readFile(req.file.path, function (err, data) {
                // 上传成功
                upyun.putFile(req.file.filename, data).then(data => {
                    console.log('上传成功', data);
                    const articleInfo = {
                        ...req.body,
                        img: domain + req.file.filename,
                    }
                    const sql = `insert into activity set ?`
                    db.query(sql, articleInfo, (err, results) => {
                        if (err) return res.cc(err)
                        if (results.affectedRows !== 1) return res.cc('增加成功失败！')
                        res.cc('增加成功！', 0)
                    })
                }).catch(err => {
                    // 上传失败
                    console.log('又拍云上传失败', err);
                });
            })
        } else {
            //跟新
        }
    })
}
// 活动列表
exports.activity = (req, res) => {
    const sql = 'select * from activity'
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取赛事数据成功！',
            data: results,
        })
    })
}
//活动详情增加
exports.addactivity_item = (req, res) => {
    const sql2 = `select * from activity where city='${req.body.city}'`
    console.log(req.body.city);
    db.query(sql2, (err, results) => {
        console.log(results);
        if (err) return res.cc(err)
        if (results.length == 0) return res.cc('城市不存在，请更换后重试！')
        if (results.length != 0) {
            if (!req.file || req.file.fieldname !== 'img') return res.cc('图片是必选参数！')
            fs.readFile(req.file.path, function (err, data) {
                // 上传成功
                upyun.putFile(req.file.filename, data).then(data => {
                    console.log('上传成功', data);
                    const articleInfo = {
                        ...req.body,
                        img: domain + req.file.filename,
                        city_id: results[0].city_id
                    }
                    const sql = `insert into activity_item set ?`
                    db.query(sql, articleInfo, (err, results) => {
                        if (err) return res.cc(err)
                        if (results.affectedRows !== 1) return res.cc('增加成功失败！')
                        res.cc('增加成功！', 0)
                    })
                }).catch(err => {
                    // 上传失败
                    console.log('又拍云上传失败', err);
                });
            })
        }
    })
}
//活动详情id内容增加
exports.addactivity_obj = (req, res) => {
    const sql2 = `select * from activity_item where id= ${req.body.obj_id}`
    db.query(sql2, (err, results) => {
        if (err) return res.cc(err)
        if (results.length == 1 && results[0].id == req.body.obj_id) return res.cc('obj_id被占用，请更换后重试！')
        if (results.length == 0) {
            if (!req.file || req.file.fieldname !== 'img') return res.cc('图片是必选参数！')
            fs.readFile(req.file.path, function (err, data) {
                // 上传成功
                upyun.putFile(req.file.filename, data).then(data => {
                    console.log('上传成功', data);
                    const articleInfo = {
                        ...req.body,
                        img: domain + req.file.filename
                    }
                    const sql = `insert into activity_obj set ?`
                    db.query(sql, articleInfo, (err, results) => {
                        if (err) return res.cc(err)
                        if (results.affectedRows !== 1) return res.cc('增加成功失败！')
                        res.cc('增加成功！', 0)
                    })
                }).catch(err => {
                    // 上传失败
                    console.log('又拍云上传失败', err);
                });
            })
        }
    })
}
//活动详情
exports.activity_item = (req, res) => {
    const sql = 'select * from activity_item where city_id=?'
    db.query(sql, req.params.city_id, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取赛事数据成功！',
            data: results,
        })
    })
}
//活动具体详情
exports.activity_obj = (req, res) => {
    const sql = 'select * from activity_obj where obj_id=?'
    db.query(sql, req.params.obj_id, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '获取赛事数据成功！',
            data: results,
        })
    })
}
// //报名
// exports.activity_bm = (req, res) => {
//     const token = req.headers.authorization.replace("Bearer ", "");
//     const secret_key = config.jwtSecretKey
//     jwt.verify(token, secret_key, (error, decoded) => {
//         if (error) {
//             console.log(`传值有问题: ${error.message}`);
//             return;
//         }
//         //查询关系表是否存在用户和该用户报名的活动
//         const sql = `select * from gxb where bm_id= ${req.body.bm_id} and open_id='${decoded.openid}'`
//         db.query(sql, (err, results1) => {
//             if (err) return res.cc(err)
//             console.log(results1);
//             if (results1.length == 1 && results1[0].bm_id == req.body.bm_id) return res.cc('bm_id被占用，请更换后重试！')
//             if (results1.length == 0) {
//                 //不存在该用户，插入
//                 const sql2 = `insert into gxb set ?`
//                 db.query(sql2, {
//                     open_id: decoded.openid,
//                     bm_id: req.body.bm_id,
//                 }, (err, results2) => {
//                     if (err) return res.cc(err)
//                     if (results2.affectedRows !== 1) return res.cc('报名失败！')
//                     if (results2.affectedRows == 1) {
//                         //查询并计算该用户参加的千米数
//                         const sql3 = `select sum(km) as total from gxb g left join activity_item a on a.id = g.bm_id where open_id='${decoded.openid}'`
//                         db.query(sql3, (err, results3) => {
//                             if (err) return res.cc(err)
//                             console.log(results3[0].total);
//                             //查询用户表是否存在该用户
//                             const sql4 = `select * from wx_users where open_id='${decoded.openid}'`
//                             db.query(sql4, (err, results4) => {
//                                 console.log('-------------跟新数据', results4);
//                                 if (results4.length > 0) {
//                                     //如果用户表存在，查询排行榜表是否存在该用户
//                                     const sql6 = `select * from charts where open_id='${decoded.openid}'`
//                                     db.query(sql6, (err, results6) => {
//                                         if (err) return res.cc(err)
//                                         if (results6.length > 0) {
//                                             //排行榜表存在用户，更新用户排名数据
//                                             const sql5 = `update charts set ? where open_id='${decoded.openid}'`
//                                             db.query(sql5, {
//                                                 kilometers: results3[0].total,
//                                                 open_id: decoded.openid,
//                                                 pic: results4[0].avatar,
//                                                 name: results4[0].nickName
//                                             }, (err, results7) => {
//                                                 if (err) return res.cc(err)
//                                                 if (results7.affectedRows == 1) {
//                                                     res.send({
//                                                         status: 200,
//                                                         message: '修改成功！',
//                                                     })
//                                                 }
//                                             })
//                                         }
//                                         if (results6.length == 0) {
//                                             //排行榜表不存在用户，插入用户排名数据
//                                             const sql5 = `insert into charts set ?`
//                                             db.query(sql5, {
//                                                 kilometers: results3[0].total,
//                                                 open_id: decoded.openid,
//                                                 pic: results4[0].avatar,
//                                                 name: results4[0].nickName
//                                             }, (err, results5) => {
//                                                 if (err) return res.cc(err)
//                                                 if (results5.affectedRows !== 1) return res.cc('报名失败！')
//                                                 if (results5.affectedRows == 1) {
//                                                     res.send({
//                                                         status: 200,
//                                                         message: '报名成功！',
//                                                     })
//                                                 }
//                                             })
//                                         }
//                                     })
//                                 }

//                             })

//                         })
//                     }
//                 })

//             }
//         })

//     });
// }


// //报名活动列表
// exports.activity_bm_list = (req, res) => {
//     const token = req.headers.authorization.replace("Bearer ", "");
//     const secret_key = config.jwtSecretKey
//     jwt.verify(token, secret_key, (error, decoded) => {
//         if (error) {
//             console.log(`传值有问题: ${error.message}`);
//             return;
//         }
//         const sql2 = `select * from gxb g left join activity_item a on a.id = g.bm_id where open_id='${decoded.openid}'`
//         db.query(sql2, (err, results) => {
//             if (err) return res.cc(err)
//             res.send({
//                 status: 200,
//                 message: '获取赛事数据成功！',
//                 data: results,
//             })
//         })
//     });
// }

//又拍云
exports.upload = (req, res) => {
    fs.readFile(req.file.path, function (err, data) {
        console.log(data);
        upyun.putFile(req.file.filename, data).then(data => {
            console.log(data);
            // 上传成功
        }).catch(err => {
            console.log('asd', err);
            // 上传失败
        });
    })
}
//排行榜获取
exports.charts = (req, res) => {
    const sql = 'select * from charts order by kilometers desc'
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 200,
            message: '排行榜成功数据成功！',
            data: results,
        })
    })
}